const mysql = require('mysql2/promise')
const config = require('../config/db')

const pool = mysql.createPool({
    host: config.db.host,
    port: config.db.port,
    user: config.db.user,
    password: config.db.password,
    database: config.db.database
})

const allServices = {
    async query(sql, values) {
        try {
            const conn = await pool.getConnection()
            const [rows] = await conn.query(sql, values)
            pool.releaseConnection(conn)
            return Promise.resolve(rows)
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

// 用户相关操作
const userLogin = (username, password) => {
    let _sql = `SELECT * FROM users WHERE username="${username}" AND password="${password}";`
    return allServices.query(_sql)
}

const findUser = (username) => {
    let _sql = `SELECT * FROM users WHERE username="${username}";`
    return allServices.query(_sql)
}

const userRegister = ({username, password, nickname, create_time}) => {
    let _sql = `INSERT INTO users (username, password, nickname, create_time) VALUES ("${username}", "${password}", "${nickname}", "${create_time}");`
    return allServices.query(_sql)
}

const findUserById = (id) => {
    let _sql = `SELECT id, username, nickname, sex, age, photo FROM users WHERE id=${id}`
    return allServices.query(_sql)
}

module.exports = {
    userLogin,
    findUser,
    userRegister,
    findUserById,

}
